package moe.util;

import java.io.UnsupportedEncodingException;

public class Base64 {
	private final static String CODE_CHAR =
			"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

	public static String encode(String input) {
		byte[] bytes = null;
		try {
			bytes = input.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
		StringBuilder result = new StringBuilder();
		int c1, c2, c3, c4;
		c1 = c2 = c3 = c4 = 0;
		for (int i = 0, length = bytes.length; i < length; i += 3) {
			try {
				c3 = bytes[i + 2];
				c4 = c3 & 63;
			} catch (IndexOutOfBoundsException e) {
				c4 = 64;
			}
			try {
				c2 = bytes[i + 1];
				c3 = ((c2 & 15) << 2) | (c3 >>> 6);
			} catch (IndexOutOfBoundsException e) {
				c3 = 64;
			}
			c1 = bytes[i];
			c2 = ((c1 & 3) << 4) | (c2 >>> 4);
			c1 = c1 >>> 2;
			result.append(CODE_CHAR.charAt(c1)).append(CODE_CHAR.charAt(c2)).append(
					CODE_CHAR.charAt(c3)).append(CODE_CHAR.charAt(c4));
		}
		return result.toString();
	}
}
